<?php

namespace Sharks\Core\Persistence;

use Sharks\Core\Support\Base\Precondition;

/**
 * Model关系
 * FIXME 暂不支持多对多
 * <pre>
 *      class ArticleContent {
 *      		...
 *
 *      		public function category() {
 *      			return RelationShip::hasOne(Category::class, 'categoryId', 'id');
 *      		}
 *      		...
 *      }
 *
 *      $article = new ArticleContent;
 *      var_dump($article->category); // Category::class
 * </pre>
 */
class RelationShip {

    const ONE_TO_ONE = 1;
    const ONE_TO_MANY = 2;
    const MANY_TO_MANY = 3;

    /**
     * 一对一关系，主关系
     * @param  string    $modelClass    关联的Model
     * @param  string   $localKey      本Model的键
     * @param  string   $otherModelKey 关联Model的键
     * @return RelationShip            
     */
    public static function hasOne($modelClass, $localKey, $foreignKey) {
    	return self::relation($modelClass, $localKey, $foreignKey, self::ONE_TO_ONE);
    }

    /**
     * 一对一关系，从属关系。主要是语义化的hasOne，与其功能无区别
     * @param  string $modelClass    [description]
     * @param  string $localKey      [description]
     * @param  string $otherModelKey [description]
     * @return string                [description]
     */
    public static function belongsTo($modelClass, $localKey, $foreignKey) {
        return self::relation($modelClass, $localKey, $foreignKey, self::ONE_TO_ONE);
    }

    /**
     * 一对多关系，主关系
     * @param  [type]  $modelClass    [description]
     * @param  [type]  $otherModelKey [description]
     * @return boolean                [description]
     */
    public static function hasMany($modelClass, $localKey, $foreignKey) {
        return self::relation($modelClass, $localKey, $foreignKey, self::ONE_TO_MANY);
    }

    protected static function relation($modelClass, $localKey, $foreignKey, $type) {
        $relationShip = new static;
        $relationShip->modelClass = $modelClass;
        $relationShip->foreignKey = $foreignKey;
        $relationShip->localKey = $localKey;
        $relationShip->type = $type;

    	return $relationShip;
    }

    protected $modelObj;
    protected $modelClass;
    protected $foreignKey;
    protected $localKey;
    protected $type;

    public function __get($name) {
        return $this->$name;
    }

    public function __set($name, $value) {
        $this->$name = $value;
    }
}